<template>
	<view class="recycle_form-container">

		<u-form :error-type="['toast']" :model="form" ref="uForm">
			<view class="recycle-devices">
				<u-form-item prop="sn">
					<u-field label="商品名称" type="input" v-model="form.name" maxlength="20" placeholder-style="#999999"
						placeholder="请输入商品名称" :border-bottom="false" label-width="180" :field-style="{
				          fontSize: '28rpx',
				          color: '\#333333'
				      }" />
				</u-form-item>

				<view>
					<u-form-item prop="classify">
						<picker mode="date" :value="form.date" @change="onSelectDateChange">
							<u-field v-model="form.date" label="购买时间" placeholder-style="#999999" placeholder="请选择购买时间"
								:border-bottom="false" label-width="180" :field-style="{
						      fontSize: '28rpx',
						      color: '\#333333'
						  }" disabled>
								<u-icon name="arrow-right" slot="right" color="#707070" size="28" />
							</u-field>
						</picker>

					</u-form-item>
				</view>


				<u-form-item prop="sn">
					<u-field label="购买价格(选填)" type="input" v-model="form.name" maxlength="20"
						placeholder-style="#999999" placeholder="请输入购买价格" :border-bottom="false" label-width="180" :field-style="{
				          fontSize: '28rpx',
				          color: '\#333333',
						  width: '120rpx'
				      }">
						<text slot="right">元</text>
					</u-field>
				</u-form-item>

				<u-form-item prop="sn">
					<u-field label="期待价值" type="input" v-model="form.name" maxlength="20" placeholder-style="#999999"
						placeholder="请输入期待价值" :border-bottom="false" label-width="180" :field-style="{
				          fontSize: '28rpx',
				          color: '\#333333'
				      }">
						<text slot="right">元</text>
					</u-field>
				</u-form-item>



			</view>



			<!-- 备注说明 -->
			<view class="recycle-remark">
				<u-form-item :border-bottom="false">
					<view class="flex1">
						<view>备注说明<text class="muted ml10">(选填)</text></view>
						<u-field v-model="form.remark" type="textarea" height="160" label-width="0" :clearable="false"
							:border-bottom="false" maxlength="240" style="line-height: 1.2em;" />
					</view>
				</u-form-item>
			</view>


			<!-- 拍照凭证 -->
			<view class="recycle-picture">
				<u-form-item :border-bottom="false">
					<view class="flex1">
						<view @tap="isShowPictureModal = true">
							<text>上传凭证</text>
							<text class="muted ml10">(请上传图片凭证)</text>
							<u-icon class="ml10" name="question-circle" color="#999999" />
						</view>
						<view class="row">
							<u-upload class="mr10" ref="uUpload" width="162" height="162" :auto-upload="false"
								:custom-btn="true" :border-bottom="false" :show-progress="false"
								@on-remove="handlePictureRemove" @on-choose-complete="handlePictureUpload">
								<view slot="addBtn" class="recycle-picture-button--upload">
									<u-icon name="/static/images/icon_camera.png" width="54" />
									<view class="xs normal">购买发票</view>
								</view>
							</u-upload>

							<u-upload class="mr10" ref="uUpload" width="162" height="162" :auto-upload="false"
								:custom-btn="true" :border-bottom="false" :show-progress="false"
								@on-remove="handlePictureRemove" @on-choose-complete="handlePictureUpload">
								<view slot="addBtn" class="recycle-picture-button--upload">
									<u-icon name="/static/images/icon_camera.png" width="54" />
									<view class="xs normal">商品图片</view>
								</view>
							</u-upload>

							<u-upload class="mr10" ref="uUpload" width="162" height="162" :auto-upload="false"
								:custom-btn="true" :border-bottom="false" :show-progress="false"
								@on-remove="handlePictureRemove" @on-choose-complete="handlePictureUpload">
								<view slot="addBtn" class="recycle-picture-button--upload">
									<u-icon name="/static/images/icon_camera.png" width="54" />
									<view class="xs normal">上传视频</view>
								</view>
							</u-upload>
						</view>

					</view>
				</u-form-item>
			</view>
		</u-form>



		<!-- Submit -->
		<view class="recycle-submit" @tap="onSubmit">提交订单</view>



		<u-modal v-model="isShowTipsModal" title=" " confirm-text="知道了">
			<view class="recycle-tips-modal">
				<image src="../../static/images/null_gift.png" mode="widthFix" class="img"></image>
				<view class="text">请耐心等待估价</view>
			</view>
		</u-modal>
	</view>
</template>


<script>
	import {
		getGoodsCategory,
		getGoodsParams,
		getSearchGoods
	} from '@/api/recycle.js'

	import {
		uploadFile
	} from '@/utils/tools.js';



	const getCurrentDate = () => {
		const date = new Date()
		const y = date.getFullYear()
		const m = date.getMonth() + 1
		const d = date.getDate()
		return `${y}-${m > 9 ? m : ('0' + m)}-${d > 9 ? d : ('0' + d)}`
	}

	export default {
		data() {
			return {
				mode: 'recycle', // 换租 || 回收
				// 表单数据
				form: {
					class_one: '1', // 一级分类
					class_oneID: '2', // 一级分类ID
					class_two: '1', // 二级分类
					class_twoID: '2', // 二级分类ID
					remark: '1', // 备注
					pictures: ['111'], // 图片
					devices: '1', // 设备型号
					params: {}, // 设备参数
					search: '', // 搜索内容
					meid: '', // MEID
					sn: '', // 序列号
					date: getCurrentDate()
				},
				isMEID: false, // 是否需要MEID的输入
				
				showClassPopup: false, // 弹出层 -> 分类
				showPopupType: 1, // 弹出层类型[一级分类 ｜ 二级分类]
				showModelPopup: false, // 弹出层 -> 型号
				oneClassifyList: [], // 一级分类列表
				twoClassifyList: [], // 二级分类列表
				goodsList: [], // 设备列表
				goodsParamsList: [], // 设备规格列表
				isShowPictureModal: false, // 拍照凭证说明 Tips
				isShowTipsModal: false,
				// 表单验证
				rules: {
					classify: [{
						validator: () => this.classify ? true : false,
						message: '请选择品牌分类',
					}],
					devices: [{
						required: true,
						message: '请选择设备型号',
					}],
					params: [{
						validator: () => {
							const params = this.form.params[this.form.devices];
							let verify = true;
							for (const [key, value] of Object.entries(params)) {
								if (!value) verify = false
							}
							return verify;
						},
						message: '请完善设备信息'
					}],
					picture: [{
						validator: () => {
							const LEN = this.form.pictures.length;
							return LEN ? true : false;
						},
						message: '请上传图片凭证'
					}],
					meid: [{
						validator: () => {
							if (!this.isMEID) return true;
							return this.form.meid ? true : false;
						},
						message: '请输入设备MEID'
					}],
					sn: [{
						validator: () => {
							if (!this.isMEID) return true;
							return this.form.sn ? true : false;
						},
						message: '请输入设备序列号'
					}],
				}
			}
		},

		computed: {
			// 品牌分类
			classify() {
				const form = this.form;
				return `${form.class_one}${form.class_one ? ' - ' : ''}${form.class_two}`;
			},
			// 型号名称
			model() {
				const model = this.goodsList.find(item => item.id == this.form.devices) || {};
				return model.name || '';
			}
		},

		methods: {
			onSelectDateChange(e) {
				this.form.date = e.detail.value
			},
			// 分类选择弹出层
			handleClassifyPopup() {
				console.log("Classify ...");
				this.showClassPopup = true;
				const mode = this.showPopupType;

				this.form.class_one ?
					this.showPopupType = 2 :
					this.showPopupType = 1;
			},

			// 选择分类一
			handleSelectClassOne(item) {
				this.form.class_oneID = item.id;
				this.goodsParamsList = [];
				this.isMEID = false;
				this.$set(this.form, 'class_one', item.name);
				getGoodsCategory({
					pid: item.id
				}).then(res => {
					if (res.code != 1) return;
					this.twoClassifyList = res.data;
				});
				// 清空分类二数据
				if (this.form.class_two) this.$set(this.form, 'class_two', '');
				this.showPopupType = 2;
			},

			// 选择分类二
			handleSelectClassTwo(item) {
				this.form.class_twoID = item.id;
				this.goodsParamsList = [];
				this.isMEID = false;
				this.$set(this.form, 'class_two', item.name);
				getGoodsCategory({
					cid: item.id
				}).then(res => {
					if (res.code != 1) return;
					this.goodsList = res.data || [];
					const params = {};
					this.goodsList.forEach(item => params[item.id] = {});
					this.$set(this.form, 'params', params);
				});
				this.showClassPopup = false;
			},

			// 点击选择型号名称
			onSelectModel() {
				if (!this.form.class_two) return uni.showToast({
					title: '请先选择品牌分类',
					icon: 'none'
				});
				this.showModelPopup = true;
			},

			// 点击搜索型号
			onSearchModel() {
				const form = this.form;
				getSearchGoods({
					cid: form.class_twoID,
					goods_name: form.search
				}).then(res => {
					if (res.code != 1) return;
					this.goodsList = res.data || [];
					const params = {};
					this.goodsList.forEach(item => params[item.id] = {});
					this.$set(this.form, 'params', params);
				});
			},

			// 选择型号
			handleSelectDevice(id) {
				this.isMEID = false;
				this.showModelPopup = false;
				this.$set(this.form, 'devices', id);
				getGoodsParams({
					re_id: id
				}).then(({
					code,
					data
				}) => {
					if (code != 1) return;
					this.goodsParamsList = data.goods_item;
					this.isMEID = !!(data.is_meid * 1);

					this.goodsParamsList.forEach(item => {
						this.$set(this.form.params[this.form.devices], item.id, '');
					});
				});
			},

			// 选择设备规格
			handleSelectParams(key, value) {
				this.$set(this.form.params[this.form.devices], key, value);
			},

			// 图片上传
			handlePictureUpload(lists, index) {
				console.log(lists);
				uni.showLoading({
					title: '正在上传中...',
					mask: true
				});

				const len = lists.length;
				const count = this.form.pictures.length;
				for (let i = count; i < len; ++i) {
					const file = {
						...lists[i]
					};

					try {
						uploadFile(file.url).then(res => {
							uni.hideLoading();
							this.form.pictures.push(res.url);
						}).catch(err => {
							uni.hideLoading();
							this.$toast(err.msg || "上传失败");
						});
					} catch (e) {
						uni.hideLoading();
						this.$toast({
							title: "上传失败"
						});
					}
				}
			},

			// 图片删除
			handlePictureRemove(index, lists, name) {
				this.form.pictures.splice(index, 1);
			},

			// 表单提交
			onSubmit() {
				// this.$refs.uForm.validate(valid => {
				// 	if (valid) {
				// 		const form = this.form;
				// 		const params = (list => {
				// 			const params = [];
				// 			for (const [key, value] of Object.entries(list)) params.push(value);
				// 			return params;
				// 		})(form.params[form.devices]);

				// 		const field = {
				// 			re_id: form.devices,
				// 			item_ids: params,
				// 			remarks: form.remark,
				// 			images: form.pictures,
				// 			// meid: form.meid,
				// 			// serial_number: form.sn
				// 			is_meid: this.isMEID
				// 		}

				// 		uni.navigateTo({
				// 			url: '/bundle/pages/recycle_price/recycle_price' +
				// 				'?order=' + JSON.stringify(field) +
				// 				'&mode=' + this.mode
				// 		});
				// 	} else {
				// 		console.log('验证失败');
				// 	}
				// });
				const form = this.form;
				// const params = (list => {
				// 	const params = [];
				// 	for (const [key, value] of Object.entries(list)) params.push(value);
				// 	return params;
				// })(form.params[form.devices]);
				
				const field = {
					re_id: form.devices,
					item_ids: {},
					remarks: form.remark,
					images: form.pictures,
					// meid: form.meid,
					// serial_number: form.sn
					is_meid: this.isMEID
				}
				
				uni.navigateTo({
					url: '/bundle/pages/recycle_price/recycle_price' +
						'?order=' + JSON.stringify(field) +
						'&mode=' + this.mode
				});
			},
		},

		onLoad(options) {
			this.mode = options.mode || 'recycle';
			// 一级分类
			getGoodsCategory().then(res => {
				if (res.code != 1) return;
				this.oneClassifyList = res.data;
			});
		},

		onReady() {
			// 表单检验
			this.$refs.uForm.setRules(this.rules);
		}
	}
</script>


<style scoped lang="scss">
	@import "index.scss";
</style>